﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Xml;
using System.IO;
using ThoughtWorks.QRCode.Codec;
using System.Diagnostics;



namespace docmgr.WinForm
{
    public enum opType
    {
        bRead,
        bEdit,
        bDelete,
        bCheck,
        bPrint
    }
    /// <summary>
    /// 常用公共类
    /// </summary>
    public class Common
    {

        /// <summary>
        /// 当前登录用户
        /// </summary>
        //public static docmgr.Model.userinfo curUser;

        public static DataTable curUser;

        /// <summary>
        /// 系统主窗体
        /// </summary>
        public static docmgr.WinForm._MainForm mainFrom;

        public static string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

        /// <summary>
        /// 当前应用程序路径,以\结尾
        /// </summary>
        public static string AppPath = "";
        public static string PrinterName = "";//打印机名字

        public static ArrayList DocType = new ArrayList();
        public static ArrayList SercretLevel = new ArrayList();

        public static ArrayList DocStatus = new ArrayList();

        public static DataTable DocClassDT = null;

        public static Form _Main = new Form();

        public static Timer sessionTimer = new Timer();
        public static Boolean sessionLogin = false;

        public static int xoffset = 0;
        public static int yoffset = 0;
        #region DataGridView表格常用功能右键菜单 新建行，删除行，查询，分组，过滤，保存布局，数据导出

        /// <summary>
        /// 将日期转化为6位数字 yy mm dd
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static String Date2Str(DateTime dt)
        {
            String xx = dt.ToString();
            String[] xxx = xx.Split(' ');
            xx = xxx[0];

            char d = xx[4];

            String[] aa = xx.Split(d);
            String tt = "";
            tt += aa[0].Substring(2, 2);
            int t1 = Convert.ToInt32(aa[1]);
            if (t1 < 10)
                tt += "0" + t1;
            else
                tt += "" + t1;

            int t2 = Convert.ToInt32(aa[2]);
            if (t2 < 10)
                tt += "0" + t2;
            else
                tt += "" + t2;

            return tt;
        }
      
        public static System.Drawing.Image qrImg(String code)
        {
            try
            {
                QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
                qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
                qrCodeEncoder.QRCodeScale = 3;
                qrCodeEncoder.QRCodeVersion = 2;
                qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
                return qrCodeEncoder.Encode(code, System.Text.Encoding.UTF8);
            }
            catch(Exception eee)
            {
                Console.WriteLine(eee.StackTrace);
            }
            return null;
        }
        

        /// <summary>
        /// 获取常用功能右键菜单，
        /// 调用举例：
        /// GlobalFun.showContextMenu(ultraGrid2, new Point(e.X, e.Y), "boya_" + this.Name, true, true);
        /// </summary>
        /// <param name="Grid">表格指针</param>
        /// <param name="pot">鼠标坐标</param>
        /// <param name="formName">布局XML文件名称</param>
        /// <param name="showAdd">是否显示新建按钮</param>
        /// <param name="showDel">是否显示删除按钮</param>
        public static System.Windows.Forms.ContextMenuStrip showContextMenu(System.Windows.Forms.DataGridView grid, System.Drawing.Point pot, string formName, bool showAdd, bool showDel)
        {
            System.Windows.Forms.ContextMenuStrip contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip();
            System.Windows.Forms.ToolStripMenuItem tsmitemNew = new System.Windows.Forms.ToolStripMenuItem();//新建
            System.Windows.Forms.ToolStripMenuItem tsmitemDel = new System.Windows.Forms.ToolStripMenuItem();//删除
            System.Windows.Forms.ToolStripMenuItem tsitemGroup = new System.Windows.Forms.ToolStripMenuItem();//分组            
            System.Windows.Forms.ToolStripMenuItem tsitemFilt = new System.Windows.Forms.ToolStripMenuItem();//过滤
            System.Windows.Forms.ToolStripMenuItem tsitemSaveStyle = new System.Windows.Forms.ToolStripMenuItem();//保存风格
            System.Windows.Forms.ToolStripMenuItem tsitemSaveAs = new System.Windows.Forms.ToolStripMenuItem();//导出到excel
            System.Windows.Forms.ToolStripMenuItem tsitemSelect = new System.Windows.Forms.ToolStripMenuItem();//自定义查询
            System.Windows.Forms.ToolStripMenuItem tsitemColSwith = new System.Windows.Forms.ToolStripMenuItem();
            System.Windows.Forms.ToolStripMenuItem tsitemResetStyle = new System.Windows.Forms.ToolStripMenuItem();

            System.Windows.Forms.ToolStripSeparator toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
            System.Windows.Forms.ToolStripSeparator toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();

            tsmitemNew.Name = "tsmitemNew";
            tsmitemNew.Size = new System.Drawing.Size(166, 22);
            tsmitemNew.Text = "新建";
            tsmitemNew.Click += new System.EventHandler(tsmitemNew_Click);
            tsmitemNew.Visible = showAdd;
            // 
            tsmitemDel.Name = "tsmitemDel";
            tsmitemDel.Size = new System.Drawing.Size(166, 22);
            tsmitemDel.Text = "删除";
            tsmitemDel.Click += new System.EventHandler(tsmitemDel_Click);
            tsmitemDel.Visible = showDel;
            // 
            toolStripSeparator2.Name = "toolStripSeparator2";
            toolStripSeparator2.Size = new System.Drawing.Size(163, 6);
            // 
           // tsitemSelect.Image = global::boya.Properties.Resources.btnGroup;
            tsitemSelect.Name = "tsitemSelect";
            tsitemSelect.Size = new System.Drawing.Size(166, 22);
            tsitemSelect.Text = "自定义查询";
            tsitemSelect.Click += new System.EventHandler(tsitemSelect_Click);           
            // 
            //tsitemGroup.Image = global::f.WinForm.Properties.Resources.btnGroup;
            tsitemGroup.Name = "tsitemGroup";
            tsitemGroup.Size = new System.Drawing.Size(166, 22);
            tsitemGroup.Enabled = true;
            //if (grid.DisplayLayout.GroupByBox.Hidden)
            //{
            tsitemGroup.Text = "开启分组";
            //}
            //else
            //{
            //    tsitemGroup.Text = "关闭分组";
            //}
            tsitemGroup.Click += new System.EventHandler(tsitemGroup_Click);
            // 
            //tsitemFilt.Image = global::f.WinForm.Properties.Resources.btFilt;
            tsitemFilt.Name = "tsitemFilt";
            tsitemFilt.Size = new System.Drawing.Size(166, 22);
            tsitemFilt.Enabled = false;
            //if (grid.DisplayLayout.Override.AllowRowFiltering == Infragistics.Win.DefaultableBoolean.Default || grid.DisplayLayout.Override.AllowRowFiltering == Infragistics.Win.DefaultableBoolean.False)
            //{
            tsitemFilt.Text = "开启过滤";
            //}
            //else
            //{
            //    tsitemFilt.Text = "关闭过滤";
            //}
            tsitemFilt.Click += new System.EventHandler(tsitemFilt_Click);

            // 
            //tsitemSaveStyle.Image = global::f.WinForm.Properties.Resources.btSaveStyle;
            tsitemSaveStyle.Name = "tsitemSaveStyle";
            tsitemSaveStyle.Size = new System.Drawing.Size(166, 22);
            tsitemSaveStyle.Text = "保存表格布局";
            tsitemSaveStyle.Tag = formName;//布局XML文件名称
            tsitemSaveStyle.Click += new System.EventHandler(tsitemSaveStyle_Click);
            // 
            //tsitemSaveAs.Image = global::f.WinForm.Properties.Resources.btnSaveAs;
            tsitemSaveAs.Name = "tsitemSaveAs";
            tsitemSaveAs.Size = new System.Drawing.Size(166, 22);
            tsitemSaveAs.Text = "导出到Excel";
            tsitemSaveAs.Click += new System.EventHandler(tsitemSaveAs_Click);

            // 
            toolStripSeparator3.Name = "toolStripSeparator3";
            toolStripSeparator3.Size = new System.Drawing.Size(163, 6);

            // 
            tsitemColSwith.Name = "tsitemColSwith";
            tsitemColSwith.Size = new System.Drawing.Size(166, 22);
            tsitemColSwith.Text = "表格列显示开关";
            tsitemColSwith.Visible = true;
            tsitemColSwith.Tag = formName;
            tsitemColSwith.Click += new System.EventHandler(tsitemColSwith_Click);
           
            // tsitemResetStyle
            //    
            tsitemResetStyle.Image = global::WinForm.Properties.Resources.del2;
            tsitemResetStyle.Name = "tsitemResetStyle";
            tsitemResetStyle.Size = new System.Drawing.Size(166, 22);
            tsitemResetStyle.Text = "清除表格布局";
            tsitemResetStyle.Tag = formName;//布局XML文件名称
            tsitemResetStyle.Visible = true;
            tsitemResetStyle.Click += new System.EventHandler(tsitemResetStyle_Click);

            contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            tsmitemNew,
            tsmitemDel,
            toolStripSeparator2,            
            tsitemGroup,
            tsitemFilt,
            tsitemSaveStyle,
            tsitemSaveAs,
            toolStripSeparator3,
            tsitemSelect,
            tsitemColSwith
            //tsitemSwithAll
            });
            contextMenuStrip1.Name = "contextMenuStrip1";
            contextMenuStrip1.Size = new System.Drawing.Size(167, 192);

            System.Drawing.Point point = grid.PointToScreen(pot);

            //弹出右键菜单
            contextMenuStrip1.Tag = grid;
            contextMenuStrip1.Show(point);
            

            return contextMenuStrip1;
        }

        #region 菜单项事件  [2012-3-16 ZhaoShunLu]//--菜单项事件
        //新建
        private static void tsmitemNew_Click(object sender, EventArgs e)
        {
            DataGridView curGrid = (DataGridView)(((ToolStripMenuItem)sender).Owner.Tag);
            if (curGrid.DataSource != null)
            {
                ((BindingSource)curGrid.DataSource).AddNew();
            }
            else
            {
                curGrid.Rows.Add();
            }

        }
        //删除
        private static void tsmitemDel_Click(object sender, EventArgs e)
        {
            DataGridView curGrid = (DataGridView)(((ToolStripMenuItem)sender).Owner.Tag);
            if (curGrid.CurrentRow != null)
            {
                curGrid.Rows.Remove(curGrid.CurrentRow);
            }
        }
        //查询
        private static void tsitemSelect_Click(object sender, EventArgs e)
        {

        }
        //分组
        private static void tsitemGroup_Click(object sender, EventArgs e)
        {
            DataGridView curGrid = (DataGridView)(((ToolStripMenuItem)sender).Owner.Tag);
        }
        //过滤
        private static void tsitemFilt_Click(object sender, EventArgs e)
        {
            DataGridView curGrid = (DataGridView)(((ToolStripMenuItem)sender).Owner.Tag);
        }
        //保存布局
        private static void tsitemSaveStyle_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem mitem = (ToolStripMenuItem)sender;
            DataGridView curGrid = (DataGridView)(mitem.Owner.Tag);//mitem.Owner菜单项的所有者
            //保存当前表格样式
            //mitem.Tag 布局XML文件名称
            string formname = mitem.Tag.ToString(); //布局XML文件名称（形式： [前缀]_[窗口名称]） 
            SaveGridStyleToXML(formname, curGrid);
        }
        //保存另存为
        private static void tsitemSaveAs_Click(object sender, EventArgs e)
        {
            DataGridView curGrid = (DataGridView)(((ToolStripMenuItem)sender).Owner.Tag);

            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "Execl files (*.xls)|*.xls";
            dlg.FilterIndex = 0;
            dlg.RestoreDirectory = true;
            dlg.CreatePrompt = true;
            dlg.Title = "保存为Excel文件";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                //返回文件路径 
                string fileNameString = dlg.FileName;
                System.IO.Stream myStream;
                myStream = dlg.OpenFile();
                System.IO.StreamWriter sw = new System.IO.StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
                string columnTitle = "";
                try
                {
                    //写入列标题
                    for (int i = 0; i < curGrid.ColumnCount; i++)
                    {
                        if (i > 0)
                            columnTitle += "\t";
                        columnTitle += curGrid.Columns[i].HeaderText;
                    }
                    sw.WriteLine(columnTitle);

                    //写入列内容
                    for (int j = 0; j < curGrid.Rows.Count; j++)
                    {
                        string columnValue = "";
                        for (int k = 0; k < curGrid.Columns.Count; k++)
                        {
                            if (k > 0)
                                columnValue += "\t";

                            if (curGrid.Rows[j].Cells[k].Value == null)
                                columnValue += "";
                            else
                                columnValue += curGrid.Rows[j].Cells[k].Value.ToString().Trim();
                        }
                        sw.WriteLine(columnValue);
                    }
                    sw.Close();
                    myStream.Close();
                    MessageBox.Show(fileNameString + "\n\n导出完毕! ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                finally
                {
                    sw.Close();
                    myStream.Close();
                }
            }
        }
       
        private static void tsitemColSwith_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem mitem = (ToolStripMenuItem)sender;
            DataGridView curGrid = (DataGridView)(mitem.GetCurrentParent().Tag);
            //保存当前表格样式
            //mitem.Tag 布局XML文件名称
            string layoutFile = mitem.Tag.ToString(); //布局XML文件名称（形式： [前缀]_[窗口名称]） 

            if (new frmColumnSelect(curGrid, layoutFile).ShowDialog() == DialogResult.OK)
            {
                Common.LoadGridStyleByXML(layoutFile,curGrid);        //存取布局文件          
            }
        }
        private static void tsitemResetStyle_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem mitem = (ToolStripMenuItem)sender;
            DataGridView curGrid = (DataGridView)(mitem.GetCurrentParent().Tag);
            //保存当前表格样式
            //mitem.Tag 布局XML文件名称
            string layoutFile = mitem.Tag.ToString() + curGrid.Name; //布局XML文件名称（形式： [前缀]_[窗口名称][表格名称]）         
            layoutFile = Common.AppPath + "config\\" + layoutFile + ".xml";
            if (System.IO.File.Exists(layoutFile))
            {
                try
                {
                    System.IO.File.Delete(layoutFile);
                    MessageBox.Show("删除布局文件成功，\r\n请关闭重新打开窗口生效！");
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("删除失败:" + ex.Message);

                }
            }
            else
            {
                MessageBox.Show("无法删除，因为没有保存过布局文件");
            }
        }
        #endregion

        /// <summary>
        /// 保存DataGridView表格样式
        /// YCSK 2010-4-25
        /// </summary>
        /// <param name="formname">窗体类的名称</param>
        /// <param name="grid">DataGridView表格</param>
        /// <returns></returns>
        public static bool SaveGridStyleToXML(string formname, System.Windows.Forms.DataGridView grid)
        {
            if (!System.IO.Directory.Exists(Common.AppPath + "Config"))
                System.IO.Directory.CreateDirectory(Common.AppPath + "Config");

            string path = Common.AppPath + "Config\\" + formname + ".xml";
            System.Xml.XmlDocument xdoc = new System.Xml.XmlDocument();
            XmlElement root;

            if (System.IO.File.Exists(path))
            {
                xdoc.Load(path);
                root = (XmlElement)xdoc.SelectSingleNode("gridStyle");//查找根节点

                //查找是否已经添加,已经存在就删除它
                XmlNode fnode = root.SelectSingleNode(grid.Name);
                if (fnode != null)
                    root.RemoveChild(fnode);
            }
            else
            {
                //新建
                XmlDeclaration dec = xdoc.CreateXmlDeclaration("1.0", "utf-8", null);
                xdoc.AppendChild(dec);

                //创建一个根节点（一级）
                root = xdoc.CreateElement("gridStyle");
                xdoc.AppendChild(root);
            }

            #region 添加表格样式  [2012-4-18 ZhaoShunLu]
            //xdoc
            XmlElement xgrid = xdoc.CreateElement(grid.Name);

            //是否是排序字段
            if (grid.SortedColumn != null)
            {
                xgrid.SetAttribute("SortedColumn", grid.SortedColumn.Name);
                xgrid.SetAttribute("SortOrder", grid.SortOrder.ToString());
            }
            else
            {
                xgrid.SetAttribute("SortedColumn", "");
                xgrid.SetAttribute("SortOrder", "");
            }

            XmlElement xrow = xdoc.CreateElement("Row");
            xrow.SetAttribute("HeadersWidth", grid.RowHeadersWidth.ToString());
            xrow.SetAttribute("Height", grid.RowTemplate.Height.ToString());
            xrow.SetAttribute("ColumnHeadersHeight", grid.ColumnHeadersHeight.ToString());
            xgrid.AppendChild(xrow);

            XmlElement xcol = xdoc.CreateElement("Columns");
            for (int i = 0; i < grid.ColumnCount; i++)
            {
                XmlElement xe = xdoc.CreateElement(grid.Columns[i].Name);//创建一个列节点
                xe.SetAttribute("Header", grid.Columns[i].HeaderText);//设置该节点ISBN属性
                xe.SetAttribute("Width", grid.Columns[i].Width.ToString());//设置该节点genre属性  
                xe.SetAttribute("Visible", grid.Columns[i].Visible.ToString());//设置该节点Displayed属性
                xe.SetAttribute("DisplayIndex", grid.Columns[i].DisplayIndex.ToString());//设置该节点DisplayIndex属性  
                xcol.AppendChild(xe);
            }
            xgrid.AppendChild(xcol);

            #endregion

            root.AppendChild(xgrid);

            xdoc.Save(path);
            return true;
        }

        /// <summary>
        /// 加载DataGridView表格样式
        /// YCSK 2010-4-25
        /// </summary>
        /// <param name="formname">窗体类的名称</param>
        /// <param name="grid">DataGridView表格</param>
        /// <returns></returns>
        public static bool LoadGridStyleByXML(string formname, System.Windows.Forms.DataGridView grid)
        {
            string path = Common.AppPath + "Config\\" + formname + ".xml";
            if (!System.IO.File.Exists(path))
            {
                //样式文件不存在
                //MessageBox.Show("样式文件不存在" + path);
                return false;
            }

            System.Xml.XmlDocument xdoc = new System.Xml.XmlDocument();
            xdoc.Load(path);
            XmlElement root = (XmlElement)xdoc.SelectSingleNode("gridStyle");//查找根节点

            //查找是否已经添加
            XmlNode gridnode = root.SelectSingleNode(grid.Name);
            if (gridnode == null)
            {
                //MessageBox.Show("表不存在");
                return false;
            }

            if (gridnode.Attributes["SortedColumn"] != null)
            {
                string sortedColumn = gridnode.Attributes["SortedColumn"].Value;
                string sortOrder = gridnode.Attributes["SortOrder"].Value;
                //MessageBox.Show("有培训 " + sortedColumn);

                if (sortedColumn != "")
                {
                    //MessageBox.Show("有培训 " + sortedColumn);
                    if (sortOrder == "Ascending")
                    {
                        //MessageBox.Show("有培训 Ascending " + sortedColumn);
                        grid.Sort(grid.Columns[sortedColumn], System.ComponentModel.ListSortDirection.Ascending);
                        grid.Columns[sortedColumn].HeaderCell.SortGlyphDirection = System.Windows.Forms.SortOrder.Ascending;
                    }
                    else
                    {
                        //MessageBox.Show("有培训 Descending " + sortedColumn);
                        grid.Sort(grid.Columns[sortedColumn], System.ComponentModel.ListSortDirection.Descending);
                        grid.Columns[sortedColumn].HeaderCell.SortGlyphDirection = System.Windows.Forms.SortOrder.Descending;
                    }
                }
            }

            XmlNode xrow = gridnode.SelectSingleNode("Row");
            grid.RowHeadersWidth = Convert.ToInt32(xrow.Attributes["HeadersWidth"].Value);
            grid.RowTemplate.Height = Convert.ToInt32(xrow.Attributes["Height"].Value);
            grid.ColumnHeadersHeight = Convert.ToInt32(xrow.Attributes["ColumnHeadersHeight"].Value);

            XmlNode xcol = gridnode.SelectSingleNode("Columns");
            for (int i = 0; i < grid.ColumnCount; i++)
            {
                XmlNode xn = xcol.SelectSingleNode(grid.Columns[i].Name);
                if (xn == null)
                {
                    //MessageBox.Show("列不存在");
                    continue;
                }
                //MessageBox.Show(xn.Attributes["Header"].Value);

                grid.Columns[i].HeaderText = xn.Attributes["Header"].Value;
                grid.Columns[i].Width = Convert.ToInt32(xn.Attributes["Width"].Value);
                grid.Columns[i].Visible = Convert.ToBoolean(xn.Attributes["Visible"].Value.ToString());
                grid.Columns[i].DisplayIndex = Convert.ToInt32(xn.Attributes["DisplayIndex"].Value.ToString());
            }

            return true;
        }

        #endregion


        #region --表格数据源

        public static string userName = "";
        /// <summary>
        /// 公用方法，将一个窗体，显示在父对象上
        /// </summary>
        /// <param name="frm">子窗体</param>
        /// <param name="parentControl">父控件</param>
        /// <returns>void</returns>
        public static void ShowFormInControl(Form frm, Control parentControl)
        {
            foreach (Control item in parentControl.Controls)
            {
                Form currentForm = item as Form;
                if (currentForm != null && (!currentForm.Equals(frm)))
                {
                    //currentForm.Close();
                    //currentForm.Dispose();
                    currentForm.Hide();
                }
            }
            frm.TopLevel = false;
            frm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            frm.Dock = DockStyle.Fill;
            frm.Parent = parentControl;
            frm.Show();
        }
        /// <summary>
        /// 公用方法，将错误、异常日志输出到根目录下制定文件中
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <param name="errorMessage">异常信息</param>
        /// <returns>void</returns>
        public static void WriteLog(string filename, string errorMessage)
        {
            string path = Directory.GetCurrentDirectory();
            string filePath = path + @"\" + filename;
            using (FileStream fs = new FileStream(filePath, FileMode.Append))
            {
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.WriteLine("-------" + errorMessage + "-------");
                }
            }
        }
        /// <summary>
        /// 公用方法，从Dictionary得到Keys列表
        /// </summary>
        /// <param name="dic">Dictionary对象引用</param>
        /// <returns>ArrayList</returns>
        public static ArrayList getList(Dictionary<string, string> dic)
        {
            ArrayList list = new ArrayList(dic.Keys);
            return list;
        }
        /// <summary>
        /// 公用方法，初始化Combox内容
        /// </summary>
        /// <param name="combox">combox控件引用</param>
        /// <param name="arryList">内容列表</param>
        /// <returns>void</returns>
        public static void initCombox(ComboBox combox, ArrayList arryList)
        {
            foreach (object obj in arryList)
            {
                if (obj.ToString() != "")
                {
                    combox.Items.Add(obj);
                }
                combox.SelectedIndex = 0;
            }
        }
        /// <summary>
        /// 公用方法，读取配置文件内容
        /// </summary>
        /// <param name="combox">combox控件引用</param>
        /// <param name="arryList">内容列表</param>
        /// <returns>string</returns>
        public static string getIniString(String fileName, string Section, string Key)
        {
            string path = Directory.GetCurrentDirectory();
            string filePath = path + @"\" + fileName;
            IniFile ini = new IniFile(filePath);
            return ini.ReadInivalue(Section, Key);
        }

        public static DataTable getDtSex()
        {
            DataTable dt = new DataTable("sex");
            dt.Columns.Add("name", typeof(string));
            dt.Columns.Add("value", typeof(int));
            DataRow dr = dt.NewRow();
            dr[0] = "男";
            dr[1] = 1;
            dt.Rows.Add(dr);
            DataRow dr2 = dt.NewRow();
            dr2[0] = "女";
            dr2[1] = 0;
            dt.Rows.Add(dr2);
            return dt;
        }
        public static DataTable getDtYes()
        {
            DataTable dt = new DataTable("Yes");
            dt.Columns.Add("name", typeof(string));
            dt.Columns.Add("value", typeof(int));
            DataRow dr = dt.NewRow();
            dr[0] = "是";
            dr[1] = 1;
            dt.Rows.Add(dr);
            DataRow dr2 = dt.NewRow();
            dr2[0] = "否";
            dr2[1] = 0;
            dt.Rows.Add(dr2);
            return dt;
        }
        public static DataTable getDtYes(bool isbool)
        {
            DataTable dt = new DataTable("Yes");
            dt.Columns.Add("name", typeof(string));
            if (isbool)
            {
                dt.Columns.Add("value", typeof(bool));
            }
            else
            {
                dt.Columns.Add("value", typeof(int));
            }
            DataRow dr = dt.NewRow();
            dr[0] = "是";
            if (isbool)
            {
                dr[1] = true;
            }
            else
            {
                dr[1] = 1;
            }
            dt.Rows.Add(dr);
            DataRow dr2 = dt.NewRow();
            dr2[0] = "否";
            if (isbool)
            {
                dr2[1] = false;
            }
            else
            {
                dr2[1] = 0;
            }
            dt.Rows.Add(dr2);
            return dt;
        }

        public static void BindComBoxForYesAndNo(System.Windows.Forms.ComboBox cbox)
        {
            cbox.DropDownStyle = ComboBoxStyle.DropDownList;
            cbox.DataSource = getDtYes();
            cbox.DisplayMember = "name";
            cbox.ValueMember = "value";
        }
        #endregion

        #region 密码及SQL安全
        public static String EncryptCode(string pwd)
        {
            /*Byte[] clearBytes = new UnicodeEncoding().GetBytes(pwd);
            Byte[] hashedBytes = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(clearBytes);
            System.Windows.Forms.MessageBox.Show(BitConverter.ToString(hashedBytes));
            String tt = BitConverter.ToString(hashedBytes).Replace("-", "");
            return tt;

           return "";*/
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(pwd, "MD5");
        }


        //sql防过滤关键字
        public static bool CheckKeyWord(string sWord)
        {
            //过滤关键字
            string StrKeyWord = @"select|insert|delete|from|count\(|drop table|update|truncate|asc\(|mid\(|char\(|xp_cmdshell|exec master|netlocalgroup administrators|:|net user|""|or|and";
            //过滤关键字符
            string StrRegex = @"[;|,|/|\(|\)|\[|\]|}|{|%|\@|*|!|']";
            if (Regex.IsMatch(sWord, StrKeyWord, RegexOptions.IgnoreCase) || Regex.IsMatch(sWord, StrRegex))
            {
                return true;
            }
            return false;


        }
        public static string getSalfSql(string sWord)
        {
            return sWord.Replace(" ", "").Replace("'", "").Replace("=", "").Replace(">", "").Replace("<", "").Replace("or", "").Replace("and", "").Replace("delete", "");
        }
        #endregion

    
        public static void ReadOffset()
        {
            string currentPath = AppDomain.CurrentDomain.BaseDirectory;
            string exepath = currentPath + "conf.ini";
            IniFile ini = new IniFile(exepath);
            Common.xoffset = Int32.Parse(ini.ReadInivalue("打印", "xoffset"));
            Common.yoffset = Int32.Parse(ini.ReadInivalue("打印", "yoffset"));
        }
        /// <summary>
        /// 下载服务器文件至客户端
        /// </summary>
        /// <param name="uri">被下载的文件地址</param>
        /// <param name="savePath">另存放的目录</param>
        public static bool Download(string uri, string savePath)
        {
            //string fileName;  //被下载的文件名
            //if (uri.IndexOf("\\") > -1) {
            //    fileName = uri.Substring(uri.LastIndexOf("\\") + 1);
            //} else {
            //    fileName = uri.Substring(uri.LastIndexOf("/") + 1);
            //}

            //if (!savePath.EndsWith("/") && !savePath.EndsWith("\\")) {
            //    savePath = savePath + "/";
            //}
            //savePath += fileName;   //另存为的绝对路径＋文件名
            System.Net.WebClient client = new System.Net.WebClient();
            try
            {
                client.DownloadFile(uri, savePath);
            }
            catch
            {
                return false;
            }

            return true;
        }

        public  static void Endding()
        {
            Common.PrinterName = "";
            Process proc = null;

            try
            {
                proc = new Process();
                proc.StartInfo.FileName=(@"End.bat");
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.CreateNoWindow = true;
                proc.Start();
                proc.WaitForExit();
            }
            catch(Exception ex)
            {

            }
        }
        public static bool DeleteFileFromServer(string uri, out string msg)
        {
            bool isok = false;

            try
            {
                System.Net.WebClient client = new System.Net.WebClient();
                System.IO.Stream myStream = client.OpenRead(uri);
                System.IO.StreamReader sr = new System.IO.StreamReader(myStream);
                string restr = sr.ReadToEnd();
                myStream.Close();

                if (restr == "ok" || restr == "ok2")
                {
                    isok = true;
                    msg = "删除文件成功！";
                }
                else if (restr == "err")
                {
                    isok = false;
                    msg = "删除文件失败。请重试！";
                }
                else
                { //undo
                    isok = false;
                    msg = "没有提供要删除的文件！";
                }
            }
            catch (System.Exception ex)
            {
                msg = "删除文件失败，发生异常：" + ex.Message;
            }
            return isok;
        }


        /// <summary>
        /// 备份数据库
        /// </summary>
        public static void BackUpDatabase(string _DBName)
        {
            string m_ConnectionStr = connectionString;
            SqlConnection _Conn = new SqlConnection(m_ConnectionStr);
            try
            {
                _Conn.Open();
                //SaveFileDialog _SaveFileDialog = new SaveFileDialog();         //保存的文件目录路径       
                //_SaveFileDialog.Title = "请选择备份保存的目录";
                //_SaveFileDialog.Filter = "(*.Bak)|*.Bak;|(All Files)|*.*";
                //if (_SaveFileDialog.ShowDialog() == DialogResult.OK)
                //{
                //string _DBName = "RelocationFiles";

                //string _FolderPath = _SaveFileDialog.FileName;
                string date = System.DateTime.Now.ToString("yyyy-MM-dd").Replace("-", "");
                string _FolderPath = "c:\\" + _DBName + " " + date + ".bak";

                SqlCommand _Comm = new SqlCommand("", _Conn);
                //执行数据库备份命令
                //_Comm.CommandText = "BACKUP DATABASE "+_DBName+" TO DISK = "+ _FolderPath +" ";
                _Comm.CommandText = "BACKUP DATABASE " + _DBName + " TO DISK = '" + _FolderPath + "' with init";//with init 覆盖
                _Comm.ExecuteNonQuery();

                _Conn.Close();
                MessageBox.Show("备份数据成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //}


            }
            catch (System.Exception error)
            {

                MessageBox.Show("异常:" + error.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        /// <summary>
        /// 恢复数据库
        /// </summary>
        public static void RestoryDatabase()
        {
            OpenFileDialog _OpenFileDialog = new OpenFileDialog();
            _OpenFileDialog.Title = "请选择文件恢复";
            _OpenFileDialog.Filter = "(*.Bak)|*.Bak;|(All Files)|*.*";

            if (_OpenFileDialog.ShowDialog() == DialogResult.OK)
            {
                string BtnRestory = _OpenFileDialog.FileName;

                if (MessageBox.Show("该操作将数据覆盖!!/n/n如果选择[是],将原来的数据覆盖/n/n如果选择[否],将取消恢复", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                    return;
                if (MessageBox.Show("请再次确认,该操作不能恢复!!/n/n如果选择[是],将原来的数据覆盖/n/n如果选择[否],将取消恢复", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
                    return;

                string m_ConnectionStr = connectionString;
                SqlConnection _Conn = new SqlConnection(m_ConnectionStr);
                try
                {
                    _Conn.Open();

                    string _FolderPath = "d:";
                    string _DBPath = "ces";
                    string _DBName = "RelocationFiles";

                    SqlCommand _Comm = new SqlCommand("restore filelistonly from disk='" + _FolderPath + @"/" + _DBPath + @".bak'", _Conn);//获得原来的逻辑名称以及物理路径
                    SqlDataReader _Reader = null;
                    _Reader = _Comm.ExecuteReader();
                    string[] _LogName = new string[2];//获得逻辑名称
                    string[] _PhiPath = new string[2];//获得物理路径
                    int j = 0;
                    while (_Reader.Read())
                    {
                        _LogName[j] = (string)_Reader.GetValue(0);
                        _PhiPath[j] = (string)_Reader.GetValue(1);
                        j = j + 1;
                    }
                    _Reader.Close();
                    MessageBox.Show(_LogName[0]);

                    //执行数据库恢复脚本
                    _Comm = new SqlCommand("", _Conn);
                    _Comm.CommandText = "RESTORE DATABASE [" + _DBName + "]   FROM DISK = '" + BtnRestory + "' With Move '" + _LogName[0] +
                        "' TO '" + _PhiPath[0] + "',  Move '" + _LogName[1] + "' TO '" + _PhiPath[1] + "'";
                    _Comm.ExecuteNonQuery();

                    MessageBox.Show("数据恢复成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    _Conn.Close();
                }
                catch (System.Exception error)
                {
                    MessageBox.Show("异常:" + error.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }


    }
    /// <summary>
    /// 表单验证类
    /// </summary>
    public class FormValidate
    {
        private static Regex RegCHZN = new Regex("[一-龥]");
        private static Regex RegCurrency = new Regex(@"^(?:[1-9][0-9]{0,2}(,[0-9]{3})*|0)\.[0-9]{2}$");
        private static Regex RegDateTime = new Regex(@"^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$");
        private static Regex RegDecimal = new Regex("^[0-9]+[.]?[0-9]+$");
        private static Regex RegDecimalSign = new Regex("^[+-]?[0-9]+[.]?[0-9]+$");
        private static Regex RegEmail = new Regex(@"^[\w-]+@[\w-]+\.(com|net|org|edu|mil|tv|biz|info)$");
        private static Regex RegNumber = new Regex("^[0-9]+$");
        private static Regex RegNumberSign = new Regex("^[+-]?[0-9]+$");
       
        /// <summary>
        /// 验证输入的数据是否合法
        /// </summary>
        /// <param name="inputData">输入数据</param>
        /// <param name="Datatype">数据类型</param>
        /// <param name="IsAllowNull">允许空或允许为Null</param>
        /// <param name="msg">返回消息</param>
        /// <returns></returns>
        public static bool CheckInput(object inputData, string Datatype, string IsAllowNull, out string msg)
        {
            msg = "";
            if ((inputData == null) || ((inputData != null) && (inputData.ToString().Trim() == "")))
            {
                if (IsAllowNull.ToLower() == "true" || IsAllowNull == "是" || IsAllowNull == "√")
                {
                    return false;
                }
                else
                {
                    msg = "不允许为空(或者是null)";
                    return true;
                }
            }

            string strInput = inputData.ToString().Trim();
            string datatype = Datatype.ToLower();

            if (datatype == "string")
            {
                //if (IsOverflow(strInput, Datatype, Length))
                //{
                //    msg = "[" + strInput + "]：长度超过(" + Length.ToString() + ")个字符(" + Datatype + ")";
                //    return true;
                //}
            }
            else if (datatype == "int" || datatype == "int64" || datatype == "int32" || datatype == "int16")
            {
                if (!IsNumber(strInput))
                {
                    msg = "你输入了[" + strInput + "]：不是数字";
                    return true;
                }
            }
            else if (datatype == "decimal" || datatype == "double")
            {
                if (!IsDecimal(strInput) && !IsNumber(strInput))
                {
                    msg = "你输入了[" + strInput + "]：不是数字";
                    return true;
                }
            }
            else if (datatype == "bool")
            {
            }
            else if (datatype == "datetime")
            {
                if (!IsDateTime(strInput))
                {
                    msg = "你输入了[" + strInput + "]：不是规定日期格式，如2010-5-12";
                    return true;
                }
            }
            else if (datatype == "money")
            {
                if (!IsCurrency(strInput))
                {
                    msg = "你输入了[" + strInput + "]：不是货币格式";
                    return true;
                }
            }

            return false;
        }

        public static bool IsCurrency(string inputData)
        {
            return RegCurrency.Match(inputData).Success;
        }
        public static bool IsDateTime(string inputData)
        {
            return RegDateTime.Match(inputData).Success;
        }
        public static bool IsDecimal(string inputData)
        {
            return RegDecimal.Match(inputData).Success;
        }
        public static bool IsDecimalSign(string inputData)
        {
            return RegDecimalSign.Match(inputData).Success;
        }
        public static bool IsEmail(string inputData)
        {
            return RegEmail.Match(inputData).Success;
        }
        public static bool IsHasCHZN(string inputData)
        {
            return RegCHZN.Match(inputData).Success;
        }
        public static bool IsNumber(string inputData)
        {
            return RegNumber.Match(inputData).Success;
        }
        public static bool IsNumberSign(string inputData)
        {
            return RegNumberSign.Match(inputData).Success;
        }    
    }
}